package run;

import java.awt.Rectangle;

import hypermedia.video.Blob;
import hypermedia.video.OpenCV;
import processing.core.PApplet;
import processing.core.PConstants;
import processing.core.PImage;
import processing.core.PVector;
import processing.video.Capture;

public class CVTest extends PApplet {

	private OpenCV opencv;
	private boolean capture_mode = true;
	private boolean display_thresh = true;
	private int contrast_lev = 20;
	private int bright_lev = 80;
	  public void setup() {
		    size(1000, 650, PConstants.P2D);
		    noStroke();
		    smooth();
		    background(255);
			frameRate(30);
			
			opencv = new OpenCV(this);
			
			if (capture_mode)
				opencv.capture( 1000, 650 );
			else
				opencv.loadImage("img.jpg");
		    
	  }
	  
	  public void draw() {
		  	if (capture_mode)
		  		opencv.read();           // grab frame from camera
		  	else
		  		opencv.loadImage("img.jpg");
		  	
		    background(255);
		  	
		  	opencv.convert(GRAY);
		    
		    opencv.contrast(contrast_lev);
		    opencv.brightness(bright_lev);
		    
		    
		    if (! display_thresh) {
		    	image(opencv.image(), 0, 0);
		    	return;
		    }

		  	opencv.threshold(5, 255, OpenCV.THRESH_OTSU );    // set black & white threshold 
		    if (display_thresh) {
		    	image(opencv.image(),0,0);
		    }
		  	
//		    image(opencv.image(), 0, 0);
		    Blob[] blobs = opencv.blobs( 100, width*height/2,
		    		100, true, OpenCV.MAX_VERTICES*4 );

		    // draw blob results
		    System.out.println(blobs.length);
		    
		    
		    for( int i=0; i<blobs.length; i++ ) {
			    fill(50);
		        beginShape();
		        for( int j=0; j<blobs[i].points.length; j++ ) {
		        	
		            int blobx = blobs[i].points[j].x;
					int bloby = blobs[i].points[j].y;
					vertex( blobx, bloby );
		        }
		        endShape(CLOSE);
		        
		        stroke(0,60,0);
		        fill(70,0,0,70);
		    	Rectangle rect = blobs[i].rectangle;
		    	rect(rect.x, rect.y, rect.width, rect.height);
		    	
		    }
		    
		    // CLASSIFY THE BLOB; if it's very square (width and height deviate by less than 10%)
		    // consider it a pipe!!!
		    for (Blob b : blobs) {
		    	Rectangle r = b.rectangle;
		    	if (abs(r.width - r.height)/(r.width) < 0.1F)
		    	{
		    		System.out.println("square blob at " + r.x + ", " + r.y);
		    		
		    		fill(0,0,90,90);
		    		rect(r.x, r.y, r.width, r.height);
		    	}
		    }
	  }
	  
	  public void keyPressed() {
		  if (key == 'a') {
			  display_thresh = true;
		  }
		  if (key == 's') {
			  display_thresh = false;
		  }
		  
		  if (key == 'k') {
			  contrast_lev++;

			  System.out.println("brightlevle " + contrast_lev);
		  }
		  if (key == 'm')
			  contrast_lev--;
		  
		  if (key=='p') {
			  bright_lev++;
			  System.out.println("brightlevle " + bright_lev);
		  }
		  if (key == 'l')
			  bright_lev --;
	  }

}
